<template>
  <div class="">
    <el-row>
      <el-col>
        <el-select v-model="queryParams.year" placeholder="选择年份" @change="handleYearChange">
          <el-option v-for="item in dict.type.biz_work_year_list" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.quarter" placeholder="选择季度" class="ml-10" @change="handleQuarterChange">
          <el-option v-for="item in quarterOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-cascader
          class="ml-10"
          v-model="queryParams.deptId"
          :options="deptOptions"
          :show-all-levels="false"
          :props="{ checkStrictly: true, value: 'deptId', label: 'deptName', checkStrictly: true, emitPath: false }"
          placeholder="选择站办所"
          filterable
          @change="handleDeptChange"
          ref="CascaderRef"
        ></el-cascader>
      </el-col>
    </el-row>
    <div class="text-banner">
      <span>干部工作情况汇总</span>
      <el-button size="mini" type="primary" circle icon="el-icon-refresh" plain @click="handleRefresh" />
    </div>
    <!-- <div v-loading="workLoading">
      <div class="float-right mb-10">
        <el-button
          icon="el-icon-s-claim"
          size="mini"
          type="primary"
          plain
          @click="handleBatchSaveOrSubmit('submit')"
          v-hasPermi="['work-assessment:cadre-supervision:submit']"
          :disabled="!selectionList.length"
          >批量提交</el-button
        >
        <el-button
          icon="el-icon-s-order"
          size="mini"
          type="warning"
          plain
          @click="handleBatchSaveOrSubmit('save')"
          class="ml-10"
          :disabled="!selectionList.length"
          v-hasPermi="['work-assessment:cadre-supervision:submit']"
          >批量保存</el-button
        >
      </div> -->

    <el-table :data="workList" border style="width: 100%" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" :selectable="checkSelectable"> </el-table-column> -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <!-- <div style="padding: 10px 20px">
                  <el-card> -->
          <el-table :data="props.row.personalWorkPlanScoreList" border stripe style="width: 100%">
            <el-table-column prop="civilServantName" label="参与人" align="center"></el-table-column>
            <el-table-column prop="workCompletionStageDict" width="150" label="完成状态" align="center">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.biz_work_completion_stage" :value="scope.row.workCompletionStageDict" />
              </template>
            </el-table-column>
            <el-table-column prop="workCompletionSituation" label="完成情况" min-width="180" align="center">
              <template slot-scope="scope">
                <span class="pre-wrap align-left">{{ scope.row.workCompletionSituation || '-' }}</span>

                <!-- <dict-tag :options="dict.type.biz_dept_important_work_completion" :value="scope.row.workCompletionSituationDict" /> -->
              </template>
            </el-table-column>
            <el-table-column prop="workCompletionMaterialUrls" label="完成材料" min-width="180" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.workCompletionMaterialUrls">
                  <el-tooltip
                    v-for="(url, index) in scope.row.workCompletionMaterialUrls.split(',')"
                    :key="index"
                    effect="dark"
                    :content="formatFileUrl(url)['name']"
                    placement="top-start"
                  >
                    <el-button type="text" @click="handlePreviewFile(url)" class="file-preview-btn">
                      {{ formatFileUrl(url)['name'] }}
                    </el-button>
                  </el-tooltip>
                </div>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="workCompletionDate" label="完成日期" width="160" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.workCompletionDate || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="firstSupervisionScore" label="站办所核查得分" width="150" align="center"></el-table-column>
            <el-table-column prop="firstSupervisionSituation" label="站办所核查情况" width="150" align="center"></el-table-column>
            <el-table-column prop="finalSupervisionScore" label="核查得分" width="130" align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.finalSupervisionScore"
                  placeholder="核查得分"
                  controls-position="right"
                  :min="0"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="finalSupervisionSituation" label="核查情况" width="150" align="center">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.finalSupervisionSituation"
                  type="textarea"
                  placeholder="输入核查情况"
                  :rows="1"
                  :autosize="{ minRows: 1, maxRows: 5 }"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
          <!-- </el-card>
                </div> -->
        </template>
      </el-table-column>

      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="workType" label="工作类型" align="center" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_work_type" :value="scope.row.workType" />
        </template>
      </el-table-column>
      <el-table-column prop="civilServantName" label="参与人" min-width="100" align="center"> </el-table-column>
      <el-table-column prop="workContent" label="工作内容" min-width="180" align="center"> </el-table-column>
      <el-table-column prop="planScore" label="分值" width="80" align="center"> </el-table-column>
      <el-table-column label="操作" align="center" width="140">
        <template slot-scope="scope">
          <div>
            <el-button
              type="text"
              size="mini"
              @click.stop="handleSaveOrSubmit(scope.row, 'save')"
              v-hasPermi="['work-assessment:cadre-supervision:submit']"
            >
              保存
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { cadreWorkAssessment } from '@/api/work-assessment'
import { list as listPlan } from '@/api/work/work-completion/cadre.js'
import { quarterFormat } from '@/utils/quarter.js'
import FilePreview from '@/components/FilePreview'
import { deptTreeSelect } from '@/api/system/user'
import { mixins } from '@/mixins'
export default {
  name: 'cadre-supervision_jxb',
  mixins: [mixins],
  dicts: ['biz_work_year_list', 'biz_work_type', 'biz_work_score_type', 'biz_work_completion_stage', 'biz_dept_important_work_completion'],
  props: {},
  components: { FilePreview },
  data() {
    return {
      keyWorkTotal: 0,
      workList: [],
      workLoading: false,
      quarterOptions: [],
      deptCivilList: [],
      deptOptions: [],
      queryParams: {
        year: '',
        quarter: '',
        workSupervisionAuditStatusDict: 'SHTG'
      },
      selectionList: []
    }
  },
  computed: {},
  watch: {},
  created() {
    ;(async () => {
      await this.getDeptTree()
      this.handleYearChange(new Date().getFullYear())
    })()
  },
  methods: {
    /** 查询站办所下拉树结构 */
    async getDeptTree() {
      await deptTreeSelect().then(response => {
        this.deptOptions = this.removeEmptyChildren(response.data)
        this.queryParams.deptId = this.deptOptions[0].deptId
      })
    },
    // 选择站办所
    handleDeptChange() {
      this.$refs.CascaderRef.dropDownVisible = false
      this.getList()
    },
    // 校验表格是否可选
    checkSelectable(raw, index) {
      if (raw.supervisionAuditStatusDict === 'SHBTG' || !raw.supervisionAuditStatusDict) {
        return true
      }
      return false
    },
    // 表格多选
    handleSelectionChange(selection) {
      this.selectionList = selection
    },
    // 批量保存or提交
    handleBatchSaveOrSubmit(operation) {
      this.handleSaveOrSubmit(this.selectionList, operation)
    },
    // 审核提示内容格式输出
    aduitContentFormat(raw) {
      let content = []
      content.push(`<p>审核意见：${raw.supervisionAuditRemark || ' - '}</p>`)
      content.push(`<p>审核时间：${raw.supervisionAuditTime || ' - '}</p>`)
      return content.join('')
    },
    // 功能类型、审核状态、提交状态
    checkBtnVisible(type, audit, submit) {
      switch (type) {
        case 'revocation':
          // 撤回
          return audit === 'DSH'
        case 'submit':
          // 提交
          return !submit && audit !== 'SHBTG'
        case 'save':
        case 'remove':
          // 保存 && 删除
          return !submit
        case 'resubmit':
          // 退回重新提交
          return audit === 'SHBTG'
        case 'finish':
          // 审核通过
          return audit === 'SHTG'
        default:
          break
      }
    },
    // 校验工作计划表单字段是否可填
    checkWorkPlanDisabled(audit) {
      if (audit === 'SHTG' || audit === 'DSH') {
        return true
      }
      return false
    },
    // 提交表单打分
    handleSaveOrSubmit(raw, operation) {
      let workSupervisionMark = false
      if (operation === 'submit') {
        workSupervisionMark = true
        let keys = Object.keys(this.workMapping)
        for (let item of raw.personalWorkPlanScoreList) {
          for (let key of keys) {
            if (!item[key] && item[key] !== 0) {
              this.$modal.msgError('操作失败！' + this.workMapping[key] + '不能为空！')
              return
            }
          }
        }
      }
      let params = { id: raw.id, workSupervisionMark, deptOperateMark: false, personalWorkResultSupervisionList: [] }
      params.personalWorkResultSupervisionList = raw.personalWorkPlanScoreList.map(item => {
        return {
          workScoreId: item.workScoreId,
          supervisionScore: item.finalSupervisionScore,
          supervisionSituation: item.finalSupervisionSituation
        }
      })
      cadreWorkAssessment(params).then(res => {
        if (operation === 'submit') {
          this.$modal.msgSuccess('已提交')
        } else if (operation === 'save') {
          this.$modal.msgSuccess('已保存')
        }
        this.handleRefresh()
      })
    },
    // 预览文件
    handlePreviewFile(url) {
      let fileItem = this.formatFileUrl(url)
      this.previewFile = { url, ...fileItem }
      this.filePreviewVisible = true
    },
    // 刷新
    handleRefresh() {
      this.getList()
    },
    // 年度选择
    handleYearChange(year) {
      this.queryParams.year = year
      // 获取当前季度、季度列表（往年默认第一季度）
      let { quarter, quarterList } = quarterFormat(year)
      this.quarterOptions = quarterList
      this.handleQuarterChange(quarter)
    },
    // 季度选择
    handleQuarterChange(quarter) {
      this.queryParams.quarter = quarter
      this.getList()
    },
    // 表格数据处理
    tableFormat(list) {
      for (let item of list) {
        item.civilServantName = item.personalWorkPlanScoreList
          .map(civil => {
            return civil.civilServantName
          })
          .join('、')
        item.personalWorkPlanScoreList.forEach(element => {
          element.workSupervisionMark = item.workSupervisionMark
          element.planScore = item.planScore
        })
      }
      this.workList = list
    },
    getList() {
      this.workLoading = true
      listPlan(this.queryParams)
        .then(res => {
          this.workLoading = false
          let { data } = res
          this.tableFormat(data)
        })
        .catch(err => (this.workLoading = false))
    }
  }
}
</script>

<style lang="scss" scoped>
.file-preview-btn {
  width: 100%;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  margin-left: 0;
  padding: 0;
}

::v-deep .el-input-number--medium {
  width: auto;
}
::v-deep .el-table__expanded-cell {
  background-color: #fafafa;
  padding: 15px;
}
</style>
